<script setup lang="ts">
import { ref, computed, watch, useAttrs } from "vue";
import { ElDialog } from "element-plus";
import user from "@/components/sql/user.vue";
import stock from "@/views/baseInfo/stock.vue";
import Row from "@/components/Row.vue";

type TypeElDialog = CPN<typeof ElDialog>;
interface Props extends /* @vue-ignore */ TypeElDialog {
  appendToBody?: boolean;
  zIndex?: number;
}
const
  props = withDefaults(defineProps<Props>(), { appendToBody: true, zIndex: 3 }),
  ua = useAttrs(),
  attrs = computed(() => {
    return { ...props, ...ua };
  }),
  data = ref<gt.sql.stock>(),
  currentTitle = computed(() => {
    if (data.value) {
      return `${data.value._group?.name}: ${data.value._goods.name} (${data.value.sum})`;
    }
  }),
  show = ref(false),
  disabled = ref(false),
  dialogTitle = ref(""),
  hs = ref(false),
  entity = ref<InstanceType<typeof user>>(),
  emit = defineEmits<{ (e: "confirm", v: gt.sql.stock): void; }>();
let cbk: cbk | undefined;
async function confirm() {
  if (data.value) {
    emit("confirm", data.value);
    cbk && cbk(data.value);
  }
  show.value = false;
}
function open(haveStock?: any) {
  hs.value = !!haveStock;
  return new Promise<gt.sql.stock | undefined>((resolve) => {
    dialogTitle.value = props.title || "选择库存";
    show.value = true;
    cbk = (p: gt.sql.stock) => {
      cbk = undefined;
      resolve(p);
    };
  });
}
watch(show, n => {
  if (!n && cbk) {
    cbk();
  }
});
defineExpose({ open });
</script>
<template>
  <ElDialog v-if="show" class="Dialog" :="attrs" :title="dialogTitle" v-model="show">
    <Row label="当前选择"><el-input :modelValue="currentTitle" placeholder="请点击下方表格进行选择" /></Row>
    <stock v-model="data" :disabled="disabled" ref="entity" :haveStock="hs" />
    <template v-if="!$slots.footer" #footer>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </ElDialog>
</template>